﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TiktokAcquisition
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // 1. UI 线程异常处理
            Application.ThreadException += Application_ThreadException;

            // 2. 非 UI 线程异常处理
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // 3. Task 异常处理（可选）
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            Application.Run(new Form1());
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception);
        }

        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            HandleException(e.Exception);
            e.SetObserved(); // 避免进程崩溃
        }

        private static async void HandleException(Exception ex)
        {
            //MessageBox.Show($"发生未处理的异常：{ex?.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            // 记录日志（如 NLog、Serilog 等）
            // Log.Error(ex, "全局异常捕获");
            await LogService.Instance.WriteErrorLog($"发生未处理的异常：{ex?.ToString()}");
            string filePath = "acquisition.json";

            try
            {
                // 2. 读取文件内容
                string jsonContent = File.ReadAllText(filePath);
                // 3. 反序列化为对象
                var data = JsonConvert.DeserializeObject<AcquisitionData>(jsonContent);
                var httpHelper = new HttpHelper(data.AcquisitionApi);
                await httpHelper.GetAsync($"/tasks/cancel_all");
            }
            catch
            {

            }

        }
    }
}
